﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.IdentityModel.Tokens.Jwt;
using tju.cme.BookStore2024.webapi.Models.Tools;
using tju.cme.BookStore2024.webapi.Models.ViewModels.Author;
using tju.cme.BookStore2024.webapi.Services;

namespace tju.cme.BookStore2024.webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorController(AuthorServices services,ILogger<AuthorController> logger):ControllerBase
    {
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            return Ok(new ReturnMessage(await services.GetAllAuthorsAsync()));
        }
        /// <summary>
        /// 作者注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("Register")]
        public async Task<IActionResult> Register(AuthorRegisterModel model)
        {
            await services.AuthorRegisterAsync(model);
            logger.LogInformation($"{model.UserName}注册成功");
            return Ok(new ReturnMessage(string.Empty));
        }

        /// <summary>
        /// 作者登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<IActionResult> Login(AuthorLoginModel model)
        {
            var token = await services.AuthorLoginAsync(model);
            logger.LogInformation($"{model.UserName}登录成功");
            return Ok(new ReturnMessage(new JwtSecurityTokenHandler().WriteToken(token)));
        }

        /// <summary>
        /// 为作者分配管理员
        /// </summary>
        /// <param name="authorId"></param>
        /// <param name="adminId"></param>
        /// <returns></returns>
        [HttpPost("AssignAdmin/{authorId}/{adminId}")]
        public async Task<IActionResult> AssignAdmin(Guid authorId, Guid adminId)
        {
            await services.AssignAdminAsync(authorId, adminId);
            return Ok(new ReturnMessage() { IsSuccess = true });
        }



        /// <summary>
        /// 根据管理员Id,返回被其管理的作者
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "Admin")]
        [HttpGet("GetAllByAdminId")]
        public async Task<IActionResult> GetAllByAdminId()
        {
            return Ok(new ReturnMessage(await services.GetAllByAdminIdAsync(GetAuthorizedInfo.GetId(User))));
        }
    }
}
